﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using DatabaseProcess;
/// <summary>
/// Summary description for Account
/// </summary>
public class Account
{
    password_encrypt pcrypt = new password_encrypt();
    
    #region tao bien
    private string _name;
    private string _username;
    private string _password;
    private DateTime _birthday;
    private string _identify_card; //CMND
    private string _address;
    private int _city;
    private int _country;
    private string _phone;
    private string _mobile;
    private string _yahoo;
    private string _email;
    private int _activation; 
    private int _type_user; // loai nguoi dung: admin/seller/buyer
    private int _id_user; // khoa chinh trong bang user
    private DateTime _dateAdd;
    private DateTime _lastModified;
    private string _link;

    public string link
    {
        get { return _link; }
        set { _link = value; }
    }

    #endregion

    #region set get

    public int userid
    {
        set { _id_user = value; }
        get { return _id_user; }
    }
    public string name
    {
        get { return _name; }
        set { _name = value; }
    }
    public string username
    {
        get { return _username; }
        set { _username = value; }
    }
    public string password
    {
        get { return _password; }
        set { _password = value; }
    }
    public DateTime birthday
    {
        get { return _birthday; }
        set { _birthday = value; }
    }
    public string identify_card
    {
        get { return _identify_card; }
        set { _identify_card = value; }
    }
    public string address
    {
        get { return _address; }
        set { _address = value; }
    }
    public int city
    {
        get { return _city; }
        set { _city = value; }
    }
    public int country
    {
        get { return _country; }
        set { _country = value; }
    }
    public string phone
    {
        get { return _phone; }
        set { _phone = value; }
    }
    public string mobile
    {
        get { return _mobile; }
        set { _mobile = value; }
    }
    public string yahoo
    {
        get { return _yahoo; }
        set { _yahoo = value; }
    }
    public string email
    {
        get { return _email; }
        set { _email = value; }
    }
    public int type_user
    {
        set { _type_user = value; }
        get { return _type_user; }
    }
    public DateTime dateAdd
    {
        get { return _dateAdd; }
        set { _dateAdd = value; }
    }

    public int activation
    {
        get { return _activation; }
        set { _activation = value; }
    }
    public DateTime lastModified
    {
        get { return _lastModified; }
        set { _lastModified = value; }
    }
    #endregion

    public Account()
    {
        //
        // TODO: Add constructor logic here
        //
        _name = ""; _identify_card = ""; _password = ""; _username = ""; _address = ""; _city = 0; _country = 0; _phone = ""; _mobile = "";
        _yahoo = ""; _email = ""; _birthday = DateTime.Now; _type_user = 3; _lastModified = DateTime.Now;
    }

    /// <summary>
    /// Kiem tra email. Su dung webservices.
    /// </summary>
    public Boolean checkEmail(string email)
    {
        //Yahoo.Sevices ya=new Yahoo.Services()
        // dung service cua yahoo va email de kiem tra.
        //---chua co viet
        return true;
    }

    public bool activeAccount()
    {
        bool result = false;
        DBconnect connect = new DBconnect();
        connect.Open();
        if (connect.IsConnected == false)
            return result;
        object[] ob = new object[] { "@ID", this.userid, "@link", this.link };
        DataTable tmp = connect.GetDataTable("users", "ID, link", "ID=@ID and link=@link", ob);
        if (tmp.Rows.Count > 0)
        {
            string sql = "UPDATE users SET activation = 1 WHERE ID = " + this.userid + " and link = '" + this.link + "'";
            connect.Execute(sql);
            result = true;
        }            
        connect.Close();
        return result;
    }


    public bool active_unactive()
    {
        bool result = false;
        DBconnect connect = new DBconnect();
        connect.Open();
        if (connect.IsConnected == false)
            return result;
        object[] ob = new object[] { "@ID", this.userid};
        DataTable tmp = connect.GetDataTable("users", "ID, activation", "ID=@ID", ob);        
        if (tmp.Rows.Count > 0)
        {
            int active = 0;
            if (Convert.ToInt32(tmp.Rows[0]["activation"].ToString()) == 0)
            {
                active = 1;
            }
            string sql = "UPDATE users SET activation = "+ active +" WHERE ID = " + this.userid;
            connect.Execute(sql);
            result = true;
        }
        connect.Close();
        return result;
    }

    /// <summary>
    /// kiem tra tai khoan nguoi dung.
    /// </summary>
    public bool Check_account()
    {
        //mã hoá mật khẩu bằng MD5        
        bool result = false;
        DBconnect connet = new DBconnect();
        connet.Open();
        if (connet.IsConnected == false)
            return result;
        string pass_encrypt = pcrypt.encryptString(this.password);
        object[] ob=new object[]{"@username",this.username,"@password",pass_encrypt};
        DataTable tmp = connet.GetDataTable("users", "ID, types_id", "username=@username and password=@password", ob);
        if(tmp.Rows.Count>0)
        {
        
            
            try
            {
                this.userid = Convert.ToInt32(tmp.Rows[0]["id"].ToString());
                this.type_user = Convert.ToInt32(tmp.Rows[0]["types_id"].ToString());
                result = true;
            }
            catch 
            {
                
                
            }
           
        }
        connet.Close();
        return result;

    }
    /// <summary>
    /// Kiem tra username da ton tai trong he thong hay chua
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    public bool checkNameAccount()
    {
        bool result = false;
        DBconnect connet = new DBconnect();
        connet.Open();
        if (connet.IsConnected == false)
            return result;
        object[] ob = new object[] { "@username", this.username};
        DataTable tmp = connet.GetDataTable("users", "username", "username=@username", ob);
        if (tmp.Rows.Count > 0)
        {
            result = true;
        }
        connet.Close();
        return result;
    }

    public bool checkEmail()
    {
        bool result = false;
        DBconnect connect = new DBconnect();
        connect.Open();
        if (connect.IsConnected == false)
            return result;
        object[] ob = new object[] { "@email", this.email };
        DataTable tmp = connect.GetDataTable("users", "email", "email=@email", ob);
        if (tmp.Rows.Count > 0)
        {
            result = true;
        }
        connect.Close();
        return result;
    }
  
    public bool checkNameDateID()
    {        
        bool result = false;
        DBconnect connect = new DBconnect();
        connect.Open();
        if (connect.IsConnected == false)
            return result;
        object[] ob = new object[] {"@identify_card", this.identify_card, "@birthday", this.birthday, "@name", this.name};
        DataTable tmp = connect.GetDataTable("users", "identify_card, birthday, name",
                                                      "identify_card=@identify_card and (birthday LIKE @birthday) and name=@name" , ob);
        if (tmp.Rows.Count > 0)
        {
            result = true;
        }
        connect.Close();
        return result;
    }
    /// <summary>
    /// Lay thong tin ve 1 Account.
    /// </summary>
    public Account GetUser(int id)
    {
        Account ac = new Account();

        DBconnect connet = new DBconnect();
        connet.Open();
        if (connet.IsConnected == false)
            return null;

        string sqlString = "select* from users where id="+id;
        DataTable result = connet.GetDataTable(sqlString);
        if (result.Rows.Count == 0)
        {
            connet.Close();
            return null;
        }
        else
        {
            ac.userid = id;
            ac.name = result.Rows[0]["name"].ToString();
            ac.username = result.Rows[0]["username"].ToString();
            ac.password = result.Rows[0]["password"].ToString();
            ac.type_user = int.Parse(result.Rows[0]["types_id"].ToString());
            ac.identify_card = result.Rows[0]["identify_card"].ToString();
            ac.yahoo = result.Rows[0]["nick_yahoo"].ToString();
            ac.email = result.Rows[0]["email"].ToString();
            ac.phone = result.Rows[0]["phone"].ToString();
            ac.mobile = result.Rows[0]["mobile_phone"].ToString();
            ac.address = result.Rows[0]["address"].ToString();
            ac.city = Convert.ToInt32(result.Rows[0]["city_id"]);
            ac.country = Convert.ToInt32(result.Rows[0]["country_id"]);
            ac.birthday = DateTime.Parse(result.Rows[0]["birthday"].ToString());
            ac.dateAdd = DateTime.Parse(result.Rows[0]["date_added"].ToString());
            ac.lastModified = DateTime.Parse(result.Rows[0]["last_modified"].ToString());
            connet.Close();
        }

        return ac;
    }

    /// <summary>
    /// Tao tai khoan nguoi dung moi.
    /// </summary>
    public int Create_Account()
    {

       
     //   ghi xuong csdl         
        DBconnect connet = new DBconnect();
        connet.Open();
        if (connet.IsConnected == false)
            return -1;
        string pass_encrypt = pcrypt.encryptString("123456");
        this.dateAdd = System.DateTime.Now;
        this.lastModified = System.DateTime.Now;
        this.identify_card = "";
        this.birthday = System.DateTime.Now;
        this.country = 1;
        this.city = 1;
        this.phone = "";
        this.yahoo = "";
        this.address = "";
        this.mobile = "";
        
        string[] listcol = new string[] { "name", "username", "password", "identify_card",
                                          "birthday","types_id" ,"nick_yahoo", "email", 
                                          "phone", "mobile_phone", "address", "city_id", 
                                          "country_id", "activation", "date_added", "last_modified" };        
        object[] listvalue = new object[] { this.name, this.username, pass_encrypt, 
                                            this.identify_card, String.Format("{0:g}", this.birthday.ToString()), this.type_user, 
                                            this.yahoo, this.email, this.phone,
                                            this.mobile, this.address, this.city, 
                                            this.country,this.activation ,String.Format("{0:g}", this.lastModified.ToString()),
                                            String.Format("{0:g}", this.dateAdd.ToString())};
        int i= connet.Insert("users",listcol,listvalue);
        connet.Close();
        return i;
    } //thieu cmnd


    public int insert_user()
    {
        DBconnect connet = new DBconnect();
        connet.Open();
        if (connet.IsConnected == false)
            return -1;
        string pass_encrypt = pcrypt.encryptString(this.password);
        this.dateAdd = System.DateTime.Now;
        this.lastModified = System.DateTime.Now;        
        this.country = 1;
        this.activation = 0;        
        this.city = 1;
        this.phone = "";
        this.yahoo = "";        
        this.mobile = "";
        
        string[] listcol = new string[] { "name", "username", "password", "identify_card",
                                          "birthday","types_id" ,"nick_yahoo", "email", 
                                          "phone", "mobile_phone", "address", "city_id", 
                                          "country_id", "activation", "date_added", "last_modified", "link"};
        object[] listvalue = new object[] { this.name, this.username, pass_encrypt, 
                                            this.identify_card, String.Format("{0:g}", this.birthday.ToString()), this.type_user, 
                                            this.yahoo, this.email, this.phone,
                                            this.mobile, this.address, this.city, 
                                            this.country,this.activation ,String.Format("{0:g}", this.lastModified.ToString()),
                                            String.Format("{0:g}", this.dateAdd.ToString()), this.link};
        int i = connet.Insert("users", listcol, listvalue);
        connet.Close();
        return i;
    } 



    /// <summary>
    /// cap nhat tai khoan nguoi dung.
    /// id: ma nguoi dung.Tra ve -1 neu fail.
    /// </summary>
    public bool UpdateAccount()
    {
        DBconnect connet = new DBconnect();
        connet.Open();
        bool result = false;
        string[] listcol = new string[] { "name", "types_id", "email", "last_modified", "birthday", "identify_card", "address" };
        object[] listvalue = new object[] { this.name, this.type_user, this.email, String.Format("{0:g}", System.DateTime.Now.ToString()), this.birthday, this.identify_card, this.address };
        string condition = "ID=@ID";
        object[] paramCondi = new object[] {"@ID",this.userid};
        int rs = connet.Update("users", listcol, listvalue, condition, paramCondi);
       if (rs > 0)
           result = true;

       connet.Close();
        return result;
    } 

    public bool DeleteAccount()
    {
        DBconnect connect = new DBconnect();
        connect.Open();
        bool result = false;
        if (connect.Delete("users", "id=@id", new object[] { "@id", this.userid }) > 0)
            result = true;
        connect.Close();
        return result;
    }
    /// <summary>
    /// khoa Account
    /// id: ma nguoi dung
    /// </summary>
    public void LockAccount(int id) 
    {
        string sql = "Update users Set activation=0 Where id=" + id;
        //----ghi xuong CSDL
        DBconnect connet = new DBconnect();
        connet.Open();
        if (connet.IsConnected)
        {
            connet.Execute(sql);
            connet.Close();
        }

    }

    /// <summary>
    /// mo khoa Account.
    /// id: ma nguoi dung
    /// </summary>
    public void UnLockAcount(int id)
    {
        string sql = "Update users Set activation=0 Where id=" + id;
        //----ghi xuong CSDL
        DBconnect connet = new DBconnect();
        connet.Open();
        if (connet.IsConnected)
        {
            connet.Execute(sql);
            connet.Close();
        }       
    }

    /// <summary>
    /// Thay doi password.
    /// id: ma nguoi dung
    /// </summary>
    public void update_password()
    {
        string pass_encrypt = pcrypt.encryptString(this.password);
        string sql = "Update users Set password='" + pass_encrypt + "' Where id = " + this.userid;
        //ghi xuong csdl;
        DBconnect connet = new DBconnect();
        connet.Open();
        if (connet.IsConnected)
        {
            connet.Execute(sql);
            connet.Close();
        }
    }

   

    public void set_permit_user(int id, int level)
    {      
        string sql = "Update users Set types_id=" + level + ", last_modified=getday()Where id=" + id;
        //ghi xuong csdl;
        DBconnect connet = new DBconnect();
        connet.Open();
        if (connet.IsConnected)
        {
            connet.Execute(sql);
            connet.Close();
        }
    }
    public DataTable getTableAccounts()
    {
        DBconnect connet = new DBconnect();
        connet.Open();
        if (connet.IsConnected == false)
            return null;
        DataTable result = new DataTable();
        string sql = "SELECT u.ID,u.username,u.password, u.name,u.nick_yahoo, u.email, u.activation, t.type_name, u.types_id, u.address, u.birthday, u.phone, u.mobile_phone FROM users u INNER JOIN user_types t ON u.types_id = t.ID";
        result = connet.GetDataTable(sql);
        connet.Close();
        return result;
    }
    public DataTable getAllAccountType()
    {
        DBconnect connet = new DBconnect();
        connet.Open();
        if (connet.IsConnected == false)
            return null;
        DataTable result = new DataTable();
        string sql = "SELECT * FROM user_types";
        result = connet.GetDataTable(sql);
        connet.Close();
        return result;
    }
}
/// <summary>
/// MD5.
/// </summary>
public class password_encrypt
{
    /// <summary>
    /// Ma hoa chuoi.
    ///strToEncrypt: chuoi can duoc ma hoa.
    /// </summary>
    public string encryptString(string strToEncrypt)
    {
        System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding();
        byte[] bytes = ue.GetBytes(strToEncrypt);

        // encrypt bytes
        System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
       
        byte[] hashBytes = md5.ComputeHash(bytes);

        // Convert the encrypted bytes back to a string (base 16)
        string hashString = "";

        for (int i = 0; i < hashBytes.Length; i++)
        {
            hashString += Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
        }

        return hashString.PadLeft(32, '0');
    }
    
    /// <summary>
    /// Xac nhan hai chuoi giong nhau.
    /// input: chuoi chua duoc ma hoa
    /// hash: chuoi da duoc ma hoa.
    /// </summary>
    public bool verifyMd5Hash(string input, string hash)
    {
        // Hash the input.
        string hashOfInput = encryptString(input);

        if (0 == String.Compare(hashOfInput, hash))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    


}
